<template>
  <div class="customer-select-group">
    <!-- 客户编码 -->
    <el-form-item v-if="showCode" label="客户编码" prop="customerCode"
      :rules="[{ required: true, message: '请选择客户编码', trigger: 'change' }]">
      <el-select clearable v-model="currentCode" placeholder="请选择客户编码" style="width: 100%;" filterable :disabled="true"
        :value-key="'customerCode'">
        <el-option :value="item.customerCode" :label="item.customerCode" :key="item.customerCode"
          v-for="item in customerList" />
      </el-select>
    </el-form-item>

    <!-- 客户名称 -->
    <el-form-item label="客户名称" prop="customerName" :rules="nameRules" ref="nameFormItem">
      <el-select clearable v-model="selectedCustomer" placeholder="请选择客户名称" style="width: 100%;" filterable
        @change="handleSelect" :value-key="'customerCode'">
        <el-option :value="item" :label="item.customerName" :key="item.customerCode" v-for="item in customerList" />
      </el-select>
    </el-form-item>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick, defineExpose } from 'vue';
import { listMesCustomerInformations } from '@/api/mes/mesCustomerInformation';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  showCode: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue']);

// 组件内部状态
const customerList = ref([]);
const selectedCustomer = ref(null);
const currentCode = ref('');
const isListLoaded = ref(false);
const nameFormItem = ref(null); // 客户名称表单项引用

// 验证规则（根据选中状态动态判断）
const nameRules = [
  {
    validator: (rule, value, callback) => {
      if (selectedCustomer.value) {
        callback(); // 已选中，验证通过
      } else {
        callback(new Error('请选择客户名称')); // 未选中，提示错误
      }
    },
    trigger: 'change',
    required: true,
  }
];

// 加载客户列表
const loadCustomerList = async () => {
  try {
    const res = await listMesCustomerInformations();
    customerList.value = res.rows || [];
    isListLoaded.value = true;
    handleEcho(props.modelValue);
  } catch (error) {
    console.error('加载客户列表失败:', error);
    isListLoaded.value = true;
  }
};

// 处理选择事件（手动触发验证）
const handleSelect = (item) => {
  if (item) {
    currentCode.value = item.customerCode;
    selectedCustomer.value = item;
    emit('update:modelValue', item.customerCode);
  } else {
    currentCode.value = '';
    selectedCustomer.value = null;
    emit('update:modelValue', '');
  }
  // 手动触发验证更新
  nextTick(() => {
    nameFormItem.value?.validate();
  });
};

// 处理回显逻辑
const handleEcho = (code) => {
  if (!code || !isListLoaded.value) return;

  nextTick(() => {
    const matched = customerList.value.find(
      item => item.customerCode === code
    );

    if (matched) {
      selectedCustomer.value = matched;
      currentCode.value = matched.customerCode;
      // 回显时手动触发验证
      nextTick(() => {
        nameFormItem.value?.validate();
      });
    } else {
      selectedCustomer.value = null;
      currentCode.value = '';
    }
  });
};

// 监听父组件值变化
watch(
  () => props.modelValue,
  (newCode) => {
    handleEcho(newCode);
  },
  { immediate: true }
);

// 暴露验证方法给父组件（可选）
defineExpose({
  validate: () => {
    return new Promise((resolve) => {
      nameFormItem.value?.validate((valid) => {
        resolve(valid);
      });
    });
  }
});

onMounted(() => {
  loadCustomerList();
});
</script>

<style scoped>
.customer-select-group {
  display: flex;
  flex-direction: column;
}
</style>